/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
 */
package td.server.handler;

import td.domain.Thought;
import td.domain.util.GetPublishedThoughtIds;
import td.domain.util.GetUnpublishedThoughtIds;
import td.server.ThoughtService;
import td.shared.action.AddThoughtAction;
import td.shared.action.result.AbstractResult.Status;
import td.shared.action.result.ThoughtResult;

import com.google.inject.Inject;
import com.gwtplatform.dispatch.server.ExecutionContext;

/**
 * A handler for Adding a Thought.
 * 
 * @author Artem Shamsutdinov
 * 
 */
public class AddThoughtHandler extends
		AbstractHandler<AddThoughtAction, ThoughtResult> {

	@Inject
	ThoughtService thoughtService;

	@Inject
	public AddThoughtHandler() {
		super(true);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doSetup(AddThoughtAction action) {
		if (action.getPublish()) {
			setThinkerLoadGroups(GetPublishedThoughtIds.class);
		} else {
			setThinkerLoadGroups(GetUnpublishedThoughtIds.class);
		}
	}

	@Override
	protected ThoughtResult doExecute(AddThoughtAction action,
			ExecutionContext context) {
		Thought newThought = thoughtService.addThought(action.getTitle(),
				action.getText(), getThinker(), action.getPublish());
		return new ThoughtResult(newThought, Status.SUCCESS, null);
	}

	@Override
	public Class<AddThoughtAction> getActionType() {
		return AddThoughtAction.class;
	}

	@Override
	protected ThoughtResult getErroneousResult(Status status, String errorMessage) {
		return new ThoughtResult(null, status, errorMessage);
	}

}
